package com.caocaog.market.toccpt.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.caocaog.market.toccpt.ccptmodel.CcOrder;
import com.caocaog.market.toccpt.marketmodel.OrderContrastCcpt;
import com.caocaog.market.toccpt.service.ApiForOrderService;
import com.caocaog.market.toccpt.service.OrderContrastCcptService;
import com.caocaog.market.toccpt.service.ToCcptService;
import com.caocaog.market.toccpt.vo.CcptOrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.toccpt.service.impl
 * @ClassName ApiForOrderServiceImpl.java
 * @createTime 2022年01月05日 11:30:00
 * @Description 向订单模块提供的api服务接口实现
 */
@Service("apiForOrderService")
@Slf4j
public class ApiForOrderServiceImpl implements ApiForOrderService {
    @Autowired
    private ToCcptService toCcptService;
    @Autowired
    private OrderContrastCcptService orderContrastCcptService;
    // 获取线上redis的连接
    // private Jedis ccJedis = new CcptJedisConfig().getJedis();
    // 向曹操跑腿自动发单
    @Override
    public Result dealMarketAutomaticOrder(String payNo) {
        log.info("向曹操跑腿自动发单");
        Result result = new Result();
        if(StringUtils.isBlank(payNo)){
            result.error500("支付流水号不能为空！");
            return result;
        }

        log.info("检测外卖订单的发单方式");
        if(!orderContrastCcptService.findOderModel(payNo)){
            log.warn("发单模式不是自动发单，不向跑腿进行自动甩单！");
            result.error500("发单模式不是自动发单，不向跑腿进行自动甩单！");
            return result;
        }

        log.info("付款成功,自动向曹操跑腿甩单");
        Result relt = toCcptService.dealOrder(payNo);
        cn.hutool.json.JSONObject reltObj = (cn.hutool.json.JSONObject)relt.getResult();

        log.info("跑腿甩单是否成功----回调信息----   "+relt.isSuccess()+"-"+relt.getMessage());
        if(relt.isSuccess()){
            log.info("向曹操跑腿甩单成功！");
            result.success("向曹操跑腿甩单成功！");
            reltObj.putOpt("isSuccess",1);
        }else{
            log.warn("向曹操跑腿甩单失败！");
            result.error500("向曹操跑腿甩单失败！");
            reltObj.putOpt("isSuccess",0);
        }
        log.info("返回的内容："+reltObj);

        log.info("添加向曹操跑腿甩单的记录");
        orderContrastCcptService.insert(reltObj);
        return result;
    }

    // 向曹操跑腿手动发单
    @Override
    public Result dealMarketManualOrder(String payNo) {
        log.info("向曹操跑腿手动发单");
        Result result = new Result();
        if(StringUtils.isBlank(payNo)){
            result.error500("支付流水号不能为空！");
            return result;
        }

        log.info("付款成功,自动向曹操跑腿甩单");
        Result relt = toCcptService.dealOrder(payNo);
        cn.hutool.json.JSONObject reltObj = (cn.hutool.json.JSONObject)relt.getResult();

        log.info("跑腿甩单是否成功----回调信息----   "+relt.getMessage());
        if(relt.isSuccess()){
            log.info("向曹操跑腿甩单成功！");
            result.success("向曹操跑腿甩单成功！");
            reltObj.putOpt("isSuccess",1);
        }else{
            log.warn("向曹操跑腿甩单失败！");
            result.error500("向曹操跑腿甩单失败！"+relt.getMessage());
            reltObj.putOpt("isSuccess",0);
        }
        log.info("返回的内容："+reltObj);

        log.info("添加向曹操跑腿甩单的记录");
        orderContrastCcptService.insert(reltObj);
        return result;
    }

    // 查询曹操跑腿的订单状态以及骑士信息等等；查询成功返回的Result中会有CcptOrderInfo对象
    @Override
    public Result findCcptOrderStatus(String marketOrderId) {
        Result result = new Result();
        // 根据曹操来了订单id去表mk_order_contrast_ccpt  查询向曹操跑腿甩单的记录
        OrderContrastCcpt orderContrastCcpt = orderContrastCcptService.findRecordByMarketOrderId(marketOrderId);
        if(null== orderContrastCcpt){
            result.error500("没有查询到该订单的甩单信息！");
            return result;
        }
        // 对应的跑腿系统中的订单id
        int ccptOrderSid = orderContrastCcpt.getCcptOrderSid();
        // 对应跑腿系统中的发单账号id
        int ccptOrderMemberSid = orderContrastCcpt.getCcptOrderMemberSid();
        /**
         * 跑腿系统中的订单状态 1：支付成功待接单，2：已接单，3：骑士到店，4：已取货/配送中，5：已送达，6：订单完成，
         *      下面的这三个状态不用管
         *      21：用户取消订单，22：代理商取消订单，23：总后台取消订单
         */
        CcOrder ccOrder = toCcptService.findCcOrderBySid(ccptOrderSid);
        int staffSid = ccOrder.getStaffSid();

        Map<String,String> map = new HashMap<>();
        // 订单状态
        CcptOrderInfo ccptOrderInfo = new CcptOrderInfo();
        ccptOrderInfo.setCcptOrderStatus(String.valueOf(ccOrder.getOrderStatus()));
        // 骑士已接单
        if(staffSid>0){
            // 骑士接单时间
            Date receiveTime = ccOrder.getReceiveTime();
            ccptOrderInfo.setCcptStaffReceiveTime(null==receiveTime ?"" : String.valueOf(receiveTime));

            // 骑士到店时间
            Date readyTime = ccOrder.getReadyTime();
            ccptOrderInfo.setCcptStaffReadyTime(null==readyTime?"":String.valueOf(readyTime));

            // 骑士取货时间
            Date takeTime = ccOrder.getTakeTime();
            ccptOrderInfo.setCcptStaffTakeTime(null==takeTime?"":String.valueOf(takeTime));

            // 骑士送达时间
            Date sendTime = ccOrder.getSendTime();
            ccptOrderInfo.setCcptStaffSendTime(null==sendTime?"":String.valueOf(sendTime));
        }
        // 获取骑士信息
        ccptOrderInfo = getStaffInfo(ccptOrderMemberSid,String.valueOf(ccptOrderSid),ccptOrderInfo);

        result.success("获取骑士信息成功");

        result.setResult(ccptOrderInfo);
        return result;
    }

    /**
     * 客户取消订单
     *      参数：曹操来了订单id
     */
    @Override
    public Result cancelOrderToCcpt(String marketOrderId) {
        Result result = new Result();
        log.info("曹操来了，ApiForOrderServiceImpl  159行，订单id= "+marketOrderId);
        if(StringUtils.isBlank(marketOrderId)){
            result.error500("161行----订单id不能为空！");
            return result;
        }
        // 根据曹操来了订单id去表mk_order_contrast_ccpt  查询向曹操跑腿甩单的记录
        OrderContrastCcpt orderContrastCcpt = orderContrastCcptService.findRecordByMarketOrderId(marketOrderId);
        if(null== orderContrastCcpt){
            result.error500("167行------没有查询到该订单的甩单信息！");
            return result;
        }
        // 对应的跑腿系统中的订单id
        int ccptOrderSid = orderContrastCcpt.getCcptOrderSid();
        /**
         * 跑腿系统中的订单状态 1：支付成功待接单，2：已接单，3：骑士到店，4：已取货/配送中，5：已送达，6：订单完成，
         *      下面的这三个状态不用管
         *      21：用户取消订单，22：代理商取消订单，23：总后台取消订单
         */
        //CcOrder ccOrder = toCcptService.findCcOrderBySid(ccptOrderSid);
        if(ccptOrderSid<1){
            result.error500("179行-------曹操跑腿订单id不能为空！");
            return result;
        }
        result = toCcptService.customerCancelOrder(ccptOrderSid);
        return result;
    }




//    public List<String> getKeys(String pattern){
//        String keyPattern = "*" + pattern + "*";
//        Set<String> setkeys = ccJedis.keys(keyPattern);
//        log.info("1520行-------->   "+setkeys);
//        if(null==setkeys || setkeys.size()<1){
//            return null;
//        }
//        List<String> resultList = new ArrayList<>(setkeys);
//        return resultList;
//    }

    private CcptOrderInfo getStaffInfo(int membersid,String orderSid,CcptOrderInfo ccptOrderInfo) {
        String str = HttpUtil.post("http://api.ccpt.xyz:9001/api/order/getorderinfo","{\"membersid\":\""+membersid+"\",\"ordersid\":\""+orderSid+"\"}");
        log.info("====>   ",str);
        // {"code":0,"data":{"tableware":null,"statusInfo":[{"value":"2022-01-04 17:01:02","key":"支付成功，等待骑士接单"},{"value":"2022-01-04 17:01:55","key":"骑士已接单，正在前往购买地"}],"orderImg":"","dispatchingtype":1,"remark":"","logInfo":null,"showDate":"2022-01-04 17:11:55","dispatchingTime":0,"sid":0,"orderTypeInfo":{"orderStatus":2,"goodsWeightText":"0-25公斤","goodsWeight":"1","goodsType":"其它","ordertype":1},"payAmount":6,"feeInfo":[{"value":6,"key":"订单金额"},{"value":6,"key":"订单起步价"},{"value":6,"key":"实际支付金额"}],"agentSid":252,"sendAndReceiptInfo":{"sendAddrAoi":"1404","sendLon":"113.777485","sendName":"曹操小店","receiptAddr":"永平路121号华启·金悦府南门","sendAddr":"河南省郑州市管城回族区正商·和谐大厦B座1404","receiptMobile":"13253396667","receiptLat":"34.739827","receiptName":"张","receiptAddrHouse":"","sendLat":"34.741837","sendMobile":"13253396667","sendAddrHouse":"","receiptAddrAoi":"永平路121号华启·金悦府南门","receiptLon":"113.776553"},"profitStatus":"","specialPrice":0,"rewardMoney":0,"createDate":"2022-01-04 17:01:02","dispatchingDis":240,"orderNo":"22010417010200686245","timePrice":0,"evaluateSid":0,"multiSplitOrder":[],"imprest":0,"payInfo":{"payTime":"2022-01-04 17:01:02","paystatus":1},"dispatchingtypeText":"电动车","staffInfo":{"staffSid":26293,"lng":"113.777436","mobile":"13253396667","name":"张昆涛","avator":"","lat":"34.741973"}},"message":"成功"}
        JSONObject jsonObject = new JSONObject(str);
        int code = Integer.parseInt(String.valueOf(jsonObject.get("code")));
        if(code==0){
            log.info("jsonObject===>   ",jsonObject);
            JSONObject data = jsonObject.getJSONObject("data");
            if(null!=data){
                log.info("data   ===>  ",data);
                JSONObject staffInfo = data.getJSONObject("staffInfo");
                if(null!=staffInfo){
                    log.info("staffInfo---->   ",staffInfo);
                    log.info("骑士姓名："+staffInfo.get("name")+" 手机号："+staffInfo.get("mobile")+"  经度："+staffInfo.get("lat")+" 纬度："+staffInfo.get("lng"));
                    ccptOrderInfo.setCcptStaffName(String.valueOf(staffInfo.get("name")));
                    ccptOrderInfo.setCcptStaffMobile(String.valueOf(staffInfo.get("mobile")));
                    ccptOrderInfo.setCcptStaffLat(String.valueOf(staffInfo.get("lat")));
                    ccptOrderInfo.setCcptStaffLng(String.valueOf(staffInfo.get("lng")));
                }
            }
        }
        return ccptOrderInfo;
    }

    public static void main(String[] args) {
        int i=1;
        System.out.println(i<2);
    }
}
